import axios from 'axios';
import { Toast } from 'vant';
// axios 基本配置
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 60000 // request timeout
});
// 请求报文配置
service.interceptors.request.use(
  (config) => {
    const settings = config;
    const { token } = sessionStorage.getItem('user') || {};
    if (token) {
      settings.headers.Authorization = `Bearer ${token}`;
    }
    return settings;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 响应报文配置
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    const { code, message } = res;
    // 如果错误非 0 ，输出错误消息
    if (code !== 0) {
      Toast.fail({
        message,
        forbidClick: true
      });
      return Promise.reject(new Error(message));
    }
    // 返回响应报文数据
    return res;
  },
  (error) => {
    console.log(`err${error}`); // for debug
    Toast.fail({
      message: error.message,
      forbidClick: true,
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
